var app = getApp();
var webhost = app.globalData.webhost;
var upLoadHost = app.globalData.upLoadHost;
var util = require('../../utils/date.js')

Page({
  data: {
    isReject:false,
    color:'',
    index: 0,
    unitIndex: 0,
    applyDate: '',
    amount: '',
    remarks: '',
    imgs: [],
    claimTypeList: [],
    claimTypeCodeList: [],
    sessionid: '',
    driverName: '',
    feeAppData: {},
    planData: {},
    data: {}
  },

  bindStatus: function(e) {
    var that = this;
    var index = e.detail.value;
    that.setData({
      index: parseInt(index)
    })
  },

  bindChargeUnit: function (e) {
    var that = this;
    var index = e.detail.value;
    that.setData({
      unitIndex: parseInt(index)
    })
  },

  inputAmount: function(e) {
    var that = this;
    var amount = that.data.amount;
    var price = that.data.price;
    var money = that.data.money;
    that.setData({
      amount: e.detail.value,
      money: e.detail.value * price
    })
  },

  inputPrice: function(e) {
    var that = this;
    var amount = that.data.amount;
    var price = that.data.price;
    var money = that.data.money;
    that.setData({
      price: e.detail.value,
      money: e.detail.value * amount
    })
  },

  inputMoney:function(e){
    this.setData({
      money: e.detail.value,
    })
  },

  inputRemarks: function(e) {
    var that = this;
    that.setData({
      remarks: e.detail.value,
    })
  },

  // 上传图片
  chooseImg: function(e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function() {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        that.setData({
          imgs: imgs
        });
      }
    });
  },

  addPhoto: function(e) {
    var that = this;
    var upPicData = that.data.upPicData
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        var url = upLoadHost;
        if (tempFilePaths) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            var now = new Date();
            var filename = upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", now);
            imgs.push(url + '/' + filename);
            wx.showToast({
              title: '图片上传中',
              icon: 'loading',
            })
            wx.uploadFile({
              url: url,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                name: tempFilePaths[i],
                key: filename,
                policy: upPicData.policy,
                OSSAccessKeyId: upPicData.accessid,
                success_action_status: "200",
                signature: upPicData.signature
              },
              success: function(res) {
                if (imgs.length <= 10) {
                  that.setData({
                    imgs: imgs
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    showCancel: false,
                    confirmColor: '#118EDE',
                    content: '图片数量不能超过10张',
                    success: function(res) {
                      if (res.confirm) {
                        imgs = imgs.slice(0, 10);
                        that.setData({
                          imgs: imgs
                        })
                      }
                    }
                  })
                }
              },
              fail() {
                wx.showToast({
                  title: '第' + i + '张图片上传失败',
                  icon: 'none'
                })
              }
            })
            wx.hideToast();
          }
        }
      }
    })
  },

  upLoadImg(tempFilePaths, i) {
    var that = this;
    var upPicData = that.data.upPicData;
    wx.showLoading({
      title: '图片上传中',
    })
    var fileName = upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", new Date());
    var url = upLoadHost;
    var imgs = that.data.imgs;
    var item = {
      picturePath: url + '/' + fileName
    }
    wx.uploadFile({
      url: url,
      filePath: tempFilePaths[i],
      name: 'file',
      formData: {
        name: tempFilePaths[i],
        key: fileName,
        policy: upPicData.policy,
        OSSAccessKeyId: upPicData.accessid,
        success_action_status: "200",
        signature: upPicData.signature
      },
      success(res) {
        imgs.push(item);
        that.setData({
          imgs: imgs
        })
        i++;
        if (i < tempFilePaths.length) {
          that.upLoadImg(tempFilePaths, i);
        } else {
          wx.hideLoading();
        }
      },
      fail() {
        wx.showToast({
          title: '第' + i + '张图片上传失败',
          icon: 'none'
        })
      }
    })
  },

  picClick() {
    var that = this;
    if (!that.data.upPicData.accessid) {
      wx.showToast({
        title: '未获取上传权限',
        icon: 'none'
      })
      return false;
    }
    var count = 9;
    count = 9 - that.data.imgs.length;
    if (count <= 0) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      })
      return false;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        if (tempFilePaths) {
          var i = 0;
          that.upLoadImg(tempFilePaths, i);
        }
      }
    })
  },


  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    var preImgs = [];
    for (var i = 0; i < imgs.length; i++) {
      preImgs[i] = imgs[i].picturePath;
    }
    wx.previewImage({
      //当前显示图片
      current: preImgs[index],
      //所有图片
      urls: preImgs
    })
  },
  
  //提交修改后的费用申请单到审核阶段
  submit: function() {
    var that = this;
    var feeAppData = that.data.feeAppData;
    if (!that.data.money) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: '#118EDE',
        content: '请输入申请金额',
        success: function(res) {
          if (res.confirm) {}
        }
      })
      return false;
    }
    var data = {
      'type': 'submit',
      id: feeAppData.id,
      reimburseNo: feeAppData.reimburseNo,
      reimburseDate: feeAppData.reimburseDate,
      reimburseAssociateNo: feeAppData.reimburseAssociateNo,
      reimburseProject: that.data.claimTypeCodeList[that.data.index],
      reimburseAmount: that.data.money,
      reimburseRemarks: that.data.remarks,
      reimburseStatus: '待审',
      n1: that.data.price,
      n2: that.data.amount,
      n3: that.data.chargeUnitCode[that.data.unitIndex]
    }
    var parameters = [{
      String: {
        driverAccount: app.globalData.driverAccount,
        sessionid: app.globalData.sessionid,
        planId: feeAppData.planId,
        taskid: feeAppData.taskid ? feeAppData.taskid : '',
        taskCode: feeAppData.taskCode,
        actionCode: 'COST',
        data: data,
        dataList: that.data.imgs
      }
    }]
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'feeApplication', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(parameters)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          var data = res.data.data;
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: '提交成功!',
            success: function(res) {
              if (res.confirm) {
                var pages = getCurrentPages();
                pages[pages.length - 2].onPullDownRefresh();
                wx.navigateBack({});
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },

  close:function(){
    wx.navigateBack({
      delta: 1
    })
  },

  //获取数据
  queryFeeApplicationDetail: function() {
    var that = this;
    var id = that.data.id;
    var sessionid = app.globalData.sessionid;
    var driverAccount = app.globalData.driverAccount;
    var data = [{
      String: {
        driverAccount: driverAccount,
        sessionid: sessionid,
        id: id
      }
    }]
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'queryFeeApplicationDetail', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(data)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          if (res.data.data.reimburseStatus == "驳回") {
            that.setData({
              isReject: true
            })
          }
          //将费用类型对齐到详情中的reimburseProject
          var data = res.data.data;
          var claimTypeList = that.data.claimTypeList;
          var claimTypeCodeList = that.data.claimTypeCodeList;
          for (var i = 0; i < claimTypeList.length;i++){
            if (data.reimburseProject == claimTypeList[i]){
              that.setData({
                index: i,
              })
              break;
            }
          }
          //将单位对齐到详情中的n11
          var chargeUnit = that.data.chargeUnit;
          console.log(that.data.chargeUnit)
          for (var j = 0; j < chargeUnit.length; j++){
            if (data.n11 == chargeUnit[j]){
              that.setData({
                unitIndex: j,
              })
            }
          }

          //将dataList中的费用类型转换为中文
          if (data) {
            for (var j = 0; j < claimTypeCodeList.length; j++) {
              if (claimTypeCodeList[j] == data.reimburseProject) {
                data.reimburseProject = claimTypeList[j];
                break;
              }
            }
          }
          // if(data.dataList && data.dataList.length > 0){
          //   var imgs = new Array;
          //   for (i = 0; i < data.dataList.length;i++){
          //     imgs[i] = data.dataList[i].picturePath
          //   }
          // }
          that.setData({
            feeAppData: data,
            amount: data.n10 || '',
            price: data.n1,
            money: data.reimburseAmount,
            remarks: data.reimburseRemarks,
            imgs: data.dataList,
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },

  onLoad: function(options) {
    var that = this;
    var curDate = util.getFormatDate();
    that.setData({
      applyDate: curDate,
      id :options.id,
      sessionid: app.globalData.sessionid,
      driverName: app.globalData.driverName
    });
    var permissionParam = [{
      String: {
        sessionid: app.globalData.sessionid
      }
    }]

    //获取计费单位
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getCodeList', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: "[{ String: { 'codeListKey': 'tsp2_chargeUnit' } }]"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        var code = res.data.code;
        var chargeUnit = [];
        var chargeUnitCode = [];
        if (code == '000000') {
          for (var i = 0; i < res.data.codeList.length; i++) {
            chargeUnit[i] = res.data.codeList[i].codeName
            chargeUnitCode[i] = res.data.codeList[i].codeValue
          }
          that.setData({
            chargeUnit: chargeUnit,
            chargeUnitCode: chargeUnitCode
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function (res) {
              if (res.confirm) { }
            }
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          confirmColor: '#118EDE',
          content: '服务器异常',
          success: function (res) {
            if (res.confirm) { }
          }
        })
      }
    })

    //拉取费用类型
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getCodeList', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: "[{ String: { 'codeListKey': 'tsp2_nameOfWayFee' } }]"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        var claimTypeList = [];
        var claimTypeCodeList = [];
        if (code == '000000') {
          for (var i = 0; i < res.data.codeList.length; i++) {
            claimTypeList[i] = res.data.codeList[i].codeName
            claimTypeCodeList[i] = res.data.codeList[i].codeValue
          }
          that.setData({
            claimTypeList: claimTypeList,
            claimTypeCodeList: claimTypeCodeList
          })

          //获取费用申请数据
          that.queryFeeApplicationDetail()
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (res.confirm) {}
            }
          })
        }
      },
      fail: function(res) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          confirmColor: '#118EDE',
          content: '服务器异常',
          success: function(res) {
            if (res.confirm) {}
          }
        })
      }
    })
    //获取上传权限
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getFileUploadPermission', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(permissionParam)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          var data = res.data.data;
          that.setData({
            upPicData: data,
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })

    

  },
  onReady:function(){
  },

  onShow: function() {

  },

  onPullDownRefresh: function() {

  },

  onShareAppMessage: function() {

  }
})